from flask import g, Blueprint, redirect, url_for, request, jsonify, session, render_template, flash
from sqlalchemy import and_

from common import Result
from exts import db, get_time
from models import User
from flask_login import current_user, login_user, logout_user, login_required

bp = Blueprint("user", __name__, url_prefix="/user")


# todo /login
@bp.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return redirect('/login')
    else:
        username = request.values.get("username")
        password = request.values.get("password")
        user = db.session.query(User).filter(and_(
            User.username == username,
            User.is_delete == 0
        )).first()
        if user is None:
            return Result.error(
                msg="没有此用户"
            )

        else:
            if user.password == password:
                # session['id_user'] = user.id
                login_user(user)
                if user.power == 0:
                    # return redirect("/admin")
                    return Result.success(
                        data="/admin"
                    )
                elif user.power == 1:
                    # return redirect("/teacher")
                    return Result.success(
                        data="/teacher"
                    )
                else:
                    # return redirect("/student")
                    return Result.success(
                        data="/student"
                    )
            else:
                return Result.error(
                    msg="密码错误"
                )


@bp.route('/update_user_and_pwd', methods=['GET', 'POST'])
@login_required
def update_user_and_pwd():
    username = request.values.get("username")
    password = request.values.get("password")
    user = g.user
    user.username = username
    user.password = password
    db.session.commit()
    return "success"


# todo /login_out
@bp.route("/login_out", methods=['GET', 'POST'])
@login_required
def login_out():
    logout_user()
    # """删除session数据"""
    # if session.get("id_user"):
    #     del session["id_user"]
    return redirect("/")
